package com.cskaoyan.wordmemorize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cskaoyan.wordmemorize.common.aspect.operate.OperateLog;
import com.cskaoyan.wordmemorize.converter.VocBookConverter;
import com.cskaoyan.wordmemorize.dao.entity.VocBookDO;
import com.cskaoyan.wordmemorize.dao.mapper.VocBookMapper;
import com.cskaoyan.wordmemorize.dto.admin.DeleteBookOperateDTO;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.dto.admin.VocBookDTO;
import com.cskaoyan.wordmemorize.request.BatchDeleteCommand;
import com.cskaoyan.wordmemorize.request.VocBookCommand;
import com.cskaoyan.wordmemorize.request.VocBookPageRequest;
import com.cskaoyan.wordmemorize.service.VocBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class VocBookServiceImpl implements VocBookService {

    @Autowired
    VocBookMapper vocBookMapper;
    @Autowired
    VocBookConverter vocBookConverter;

    /**
     * 分页展示单词书籍(后端-物料管理-书籍管理)
     * @param pageQuery
     * @return
     */
    @Override
    public PageDTO<VocBookDTO> getBookPage(VocBookPageRequest pageQuery) {
        LambdaQueryWrapper<VocBookDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VocBookDO::getIsDeleted, 0);
        if (pageQuery.getCategoryId() != null && !pageQuery.getCategoryId().trim().isEmpty()) {
            wrapper.eq(VocBookDO::getBcId, pageQuery.getCategoryId());
        }
        if (pageQuery.getKeyword() != null && !pageQuery.getKeyword().trim().isEmpty()) {
            wrapper.and(w -> w.like(VocBookDO::getName, pageQuery.getKeyword())
                    .or().like(VocBookDO::getAuthor, pageQuery.getKeyword()));
        }
        wrapper.orderByAsc(VocBookDO::getSortBy);

        // 支持分页和查询全部
        if (pageQuery.getPageNum() == null || pageQuery.getCount() == null) {
            List<VocBookDO> all = vocBookMapper.selectList(wrapper);
            return vocBookConverter.vocBookList2Page(all, (long) all.size());
        } else {
            Page<VocBookDO> page = new Page<>(pageQuery.getPageNum(), pageQuery.getCount());
            Page<VocBookDO> result = vocBookMapper.selectPage(page, wrapper);
            return vocBookConverter.vocBookList2Page(result.getRecords(), result.getTotal());
        }
    }

    /**
     * 添加单词书籍(后端-物料管理-书籍管理)
     * @param command
     * @return
     */
    @Override
    @OperateLog(dataType = "书籍", operateType = 1, description = "新增书籍")
    public Long addVocBook(VocBookCommand command) {
        VocBookDO entity = vocBookConverter.vocBookCommand2VocBookDO(command);
        vocBookMapper.insert(entity);
        return entity.getId();
    }

    /**
     * 更新单词书籍(后端-物料管理-书籍管理)
     * @param command
     */
    @Override
    @OperateLog(dataType = "书籍", operateType = 4, description = "修改书籍")
    public void updateVocBook(VocBookCommand command) {
        VocBookDO entity = vocBookConverter.vocBookCommand2VocBookDO(command);
        entity.setId(Long.valueOf(command.getId())); // 确保更新时有主键
        vocBookMapper.updateById(entity);
    }

    /**
     * 删除单词书籍(后端-物料管理-书籍管理)
     * @param bookId
     * @return
     */
    @Override
    @Transactional
    @OperateLog(dataType = "书籍", operateType = 2, description = "删除书籍", logReturnValue = true)
    public DeleteBookOperateDTO deleteVocBook(Long bookId) {
        VocBookDO book = vocBookMapper.selectById(bookId);
        if (book == null || (book.getIsDeleted() != null && book.getIsDeleted() == 1)) {
            // 已经被删除或不存在
            return null;
        }
        vocBookMapper.deleteById(bookId);
        return vocBookConverter.vocBookDO2DeleteBookDTO(book);
    }

    /**
     * 批量删除选中的单词书籍(后端-物料管理-书籍管理)
     * @param command
     * @return
     */
    @Override
    @Transactional
    @OperateLog(dataType = "书籍", operateType = 3, description = "批量删除书籍", logReturnValue = true)
    public List<DeleteBookOperateDTO> deleteVocBooks(BatchDeleteCommand command) {
        List<String> ids = command.getIds();
        if (ids == null || ids.isEmpty())
            return Collections.emptyList();

        List<DeleteBookOperateDTO> deletedBooks = new ArrayList<>();
        for (String idStr : ids) {
            try {
                Long id = Long.valueOf(idStr);
                DeleteBookOperateDTO dto = deleteVocBook(id);
                if (dto != null) {
                    deletedBooks.add(dto);
                }
            } catch (NumberFormatException e) {
                // 可以记录日志，说明有非法ID
            }
        }
        return deletedBooks;
    }
}
